/**
 * 基础设计
 * @constructor
 */
var ReportBaseDesign = function ($grid_selector, reportCategory, url, rowData) {

    // 报表表格jq对象
    this.$grid_selector = $grid_selector;
    // 报表分类
    this.reportCategory = reportCategory;
    // 报表设计元数据表格
    this.reportMateTable = null;
    // 报表设计参数表格
    this.reportParamTable = null;
    // 编辑与新增的form
    this.$form_report = null;
    // 参数设计form
    this.$form_report_param = null;
    // form的action url
    this.url = url || '';
    // 当前编辑报表的行数据
    this.rowData = rowData || {};

    // 基础设计模版
    this.baseTemplate = _.template('\
    <div style="padding: 12px 21px 12px 12px; ">\
        <form class="form-horizontal" id="form_report" method="PUT">\
            <input hidden="hidden" id="rId" name="rId">\
            <div class="form-group">\
                <label for="name" class="control-label col-xs-1">名称</label>\
                <div class="col-xs-5">\
                    <input autocomplete="off" class="form-control" id="name" name="name">\
                </div>\
                <label for="status" class="control-label col-xs-1">状态</label>\
                <div class="col-xs-5">\
                    <label style="padding-top: 7px;">\
                        <input id="status" class="ace ace-switch ace-switch-3" type="checkbox">\
                        <span class="lbl"></span>\
                    </label>\
                </div>\
            </div>\
            <div class="form-group">\
                <label for="rcId" class="control-label col-xs-1">分类</label>\
                <div class="col-xs-5">\
                    <select readonly autocomplete="off" class="form-control" id="rcId" name="rcId">\
                    </select>\
                </div>\
                <label for="rdsId" class="col-xs-1 control-label">数据源</label>\
                <div class="col-xs-5">\
                    <select autocomplete="off" class="form-control" id="rdsId" name="rdsId"></select>\
                </div>\
            </div>\
            <div class="form-group">\
                <label for="sql" class="control-label col-xs-1">SQL</label>\
                <div class="col-xs-11">\
                    <textarea class="form-control" id="sql" name="sql"></textarea>\
                </div>\
            </div>\
        </form>\
        {{footer}}\
    </div>\
    ');

    // 参数设计模版
    this.paramTemplate = _.template('\
    <div style="padding: 12px;">\
        <form class="form-horizontal" id="form_report_param">\
            <div class="form-group">\
                <label for="name" class="control-label col-xs-1">参数名称</label>\
                <div class="col-xs-2">\
                    <input type="text" name="name" class="form-control" id="name" autocomplete="off">\
                </div>\
                <label for="title" class="control-label col-xs-1">标题</label>\
                <div class="col-xs-2">\
                    <input type="text" name="title" class="form-control" id="title" autocomplete="off">\
                </div>\
                <label for="defaultValue" class="control-label col-xs-1">默认值</label>\
                <div class="col-xs-2">\
                    <input type="text" name="defaultValue" class="form-control" id="defaultValue" autocomplete="off">\
                </div>\
                <label for="defaultLabel" class="control-label col-xs-1">默认标签</label>\
                <div class="col-xs-2">\
                    <input type="text" class="form-control" name="defaultLabel" id="defaultLabel" autocomplete="off">\
                </div>\
            </div>\
            <div class="form-group">\
                <label for="dataType" class="control-label col-xs-1">参数类型</label>\
                <div class="col-xs-2">\
                    <select name="dataType" id="dataType" class="form-control" autocomplete="off">\
                        <option value="1">字符串</option>\
                        <option value="2">浮点数</option>\
                        <option value="3">整形数</option>\
                        <option value="4">日期</option>\
                    </select>\
                </div>\
                <label for="controlType" class="control-label col-xs-1">表单控件</label>\
                <div class="col-xs-2">\
                    <select class="form-control" name="controlType" id="controlType" autocomplete="off">\
                        <option value="1">下拉框单选</option>\
                        <option value="2">下拉框多选</option>\
                        <option value="3">日期</option>\
                        <option value="4">文本</option>\
                        <option value="5">复选框</option>\
                    </select>\
                </div>\
                <label for="source" class="control-label col-xs-1">内容来源</label>\
                <div class="col-xs-2">\
                    <select name="sourceType" id="sourceType" class="form-control" autocomplete="off">\
                        <option value="1">sql查询</option>\
                        <option value="2">文本</option>\
                        <option value="3">无内容</option>\
                    </select>\
                </div>\
                <label for="optional" class="control-label col-xs-1">是否必选</label>\
                <div class="col-xs-2" style="padding-top: 7px;">\
                    <input id="optional" name="optional" autocomplete="off" class="ace ace-switch ace-switch-3" type="checkbox" checked="checked">\
                    <span class="lbl"></span>\
                </div>\
            </div>\
            <div class="form-group">\
                <label for="content" class="control-label col-xs-1">内容</label>\
                <div class="col-xs-11">\
                    <textarea rows="8" name="content" id="content" class="form-control" autocomplete="off"></textarea>\
                </div>\
            </div>\
        </form>\
        <div class="row">\
        <div class="col-xs-12">\
            <div class="btn-group center-block" style="width: 240px; height: 45px; margin-left: auto;">\
                <button id="report_param_add" class="btn btn-success btn-sm" type="button"><i class="ace-icon fa fa-check"></i>新增</button>\
                <button id="report_param_del" class="btn btn-danger btn-sm" type="button"><i class="ace-icon fa fa-trash align-top bigger-125"></i>删除</button>\
                <button id="report_param_edit" class="btn btn-primary btn-sm" type="button"><i class="ace-icon fa fa-pencil align-top bigger-125"></i>修改</button>\
            </div>\
        </div>\
        </div>\
        {{footer}}\
    </div>');
};
// 类属性
ReportBaseDesign.URL = {
    DESIGN_ADD: '/report/design',
    DESIGN_EDIT: '/report/design/{{id}}',
    DATA_SOURCE_GET: '/report/datasource/get/rid',
    REPORT_DESIGN_RENDER: '/report/design/render/query'
};
ReportBaseDesign.prototype = {

    init: function () {

        var self = this;
        this.reportMateTable = new ReportMateTable();
        this.reportParamTable = new ReportParamTable();
        var config = {
            area: ['90%', '95%'],
            btn: ['预览', '保存', '取消'],
            tab: [{
                title: '基础设计',
                content: this.baseTemplate({ footer: self.reportMateTable.view })
            }, {
                title: '参数设计',
                type: 2,
                content: this.paramTemplate({ footer: self.reportParamTable.view })
            }],
            btn1: function (index, layero) {
                self.layerBtn1Action(index, layero);
            },
            btn2: function (index, layero) {
                return self.layerBtn2Action(index, layero)
            },
            btn3: function (index, layero) {
                return self.layerBtn3Action(index, layero);
            },
            success: function (layero, index) {
                return self.layerSuccessAction(layero, index);
            }
        };
        layer.tab(config);
    },
    layerBtn1Action: function (index, layero) {

        this.$form_report.attr('action', ReportBaseDesign.URL.REPORT_DESIGN_RENDER).validate({
            rules: {
                name: { required: true },
                rdsId: { required: true },
                rcId: { required: true },
                sql: { required: true }
            }
        });
        // 验证成功
        var status = this.$form_report.find('[id=status]').is(':checked');
        $.xumf.showLoading();
        this.$form_report.valid() && this.$form_report.ajaxSubmit({
            data: {
                metaColumns: JSON.stringify(this.reportMateTable.trData),
                queryParams: JSON.stringify(this.reportParamTable.trData),
                status: status ? 1 : 0
            },
            success: function (res) {
                $.xumf.hideLoading();
                layer.open({
                    content: res,
                    area: ['60%', '45%'],
                    end: function () {
                        if (undefined !== window.reportChart) {
                            // 销毁echarts实例
                            window.reportChart.dispose();
                            window.reportChart = undefined;
                        }
                    }
                });
            }
        });
        return false;
    },
    layerBtn2Action: function (index, layero) {

        var self = this;
        var rId = this.$form_report.find('input[name=rId]').val();
        var type, url;
        if (ReportBaseDesign.URL.DESIGN_ADD === this.url) {
            url = this.url;
            type = 'POST';
        } else {
            url = _.template(this.url)({ id: rId });
            type = 'PUT';
        }
        this.$form_report.validate({
            rules: {
                name: { required: true },
                rdsId: { required: true },
                rcId: { required: true },
                sql: { required: true }
            }
        });
        // 验证成功
        var status = this.$form_report.find('[id=status]').is(':checked');
        this.$form_report.valid() && this.$form_report.ajaxSubmit({
            url: url,
            type: type,
            data: {
                metaColumns: JSON.stringify(self.reportMateTable.trData),
                queryParams: JSON.stringify(self.reportParamTable.trData),
                status: status ? 1 : 0
            },
            success: function (res) {
                self.$grid_selector.trigger('reloadGrid');
                $.xumf.gritter(res);
            }
        });
        return false;
    },
    layerBtn3Action: function (index, layero) {

        var self = this;
        $.xumf.confirm('是否保存更改？', function (idx, lay) {
            self.layerBtn2Action(index, layero);
            layer.close(idx);
            layer.close(index);
        }, function (idx, lay) {
            layer.close(idx);
            layer.close(index);
        });
        return false;
    },
    layerSuccessAction: function (layero, index) {

        // 获取当前选择分类
        var nodes = this.reportCategory.treeObj.getSelectedNodes();
        if (nodes.length === 0) {
            $.xumf.gritterError('请选择报表分类！');
            layer.closeAll();
            return false;
        }

        this.$form_report = $('#form_report');
        this.$form_report_param = $('#form_report_param');
        // 解决layer不能有空白空位的bug
        this.$form_report.closest('.layui-layer-content').css('width', '100%');
        this.$form_report_param.closest('.layui-layer-content').css('width', '100%');
        // 去掉ul黑点
        this.$form_report.closest('ul').css({ 'list-style': 'none', 'margin-left': '0px' });
        // 初始化界面数据
        this.initBaseDesign(nodes[0]);
        this.initParamDesign(nodes[0]);
    },
    initParamDesign: function () {
        var self = this;
        var $form = self.$form_report_param;

        /**
         * 验证表单内容
         * @returns {*}
         */
        function valid() {
            $form.validate({
                rules: {
                    name: { maxlength: 100, required: true },
                    title: { maxlength: 25, required: true },
                    // length: {digits: true, required: true},
                    defaultValue: { required: true },
                    defaultLabel: { required: true },
                    controlType: { required: true },
                    sourceType: { required: true },
                    dataType: { required: true },
                    content: { required: true }
                }
            });
            return $form.valid();
        }

        /**
         * 获取表单数据
         * @returns {{name: *|{}, title: *|{}, defaultValue: *|{}, defaultLabel: *|{}, controlType: *|{}, sourceType: *|{}, dataType: *|{}, optional: *|{}, content: *|{}}}
         */
        function getFormData() {
            return {
                name: $form.find('[name=name]').val(),
                title: $form.find('[name=title]').val(),
                defaultValue: $form.find('[name=defaultValue]').val(),
                defaultLabel: $form.find('[name=defaultLabel]').val(),
                controlType: $form.find('[name=controlType]').val(),
                sourceType: $form.find('[name=sourceType]').val(),
                dataType: $form.find('[name=dataType]').val(),
                optional: $form.find('[name=optional]').is(':checked'),
                content: $form.find('[name=content]').val()
            };
        }

        // 参数设计表格tr选中事件
        $('#' + self.reportParamTable.tableId).on('report.param.tr.selected', function (e, selectedData) {
            $form.find('[name=name]').val(selectedData.name);
            $form.find('[name=title]').val(selectedData.title);
            $form.find('[name=defaultValue]').val(selectedData.defaultValue);
            $form.find('[name=defaultLabel]').val(selectedData.defaultLabel);
            $form.find('[name=controlType]').val(selectedData.controlType);
            $form.find('[name=sourceType]').val(selectedData.sourceType);
            $form.find('[name=dataType]').val(selectedData.dataType);
            $form.find('[name=optional]').val(selectedData.optional);
            $form.find('[name=content]').val(selectedData.content);
        });
        // 添加参数设计 添加事件
        $('#report_param_add').on('click', function (e) {
            valid() && self.reportParamTable.addRow(getFormData());
            e.preventDefault();
        });
        // 添加参数设计 删除事件
        $('#report_param_del').on('click', function (e) {
            self.reportParamTable.removeRow();
            e.preventDefault();
        });
        // 添加参数设计 编辑事件
        $('#report_param_edit').on('click', function (e) {
            valid() && self.reportParamTable.editRow(getFormData());
            e.preventDefault();
        });
        this.reportParamTable.addRows(JSON.parse(this.rowData.queryParams || '[]'));
    },
    /**
     * 初始化基础设计
     * @param node
     */
    initBaseDesign: function (node) {

        // 添加table事件
        this.reportMateTable.byDelegateEvent();
        var rowData = this.rowData;
        this.initSqlEditor();
        this.$form_report.find('[id=rId]').val(rowData.rId || 0);
        this.$form_report.find('[id=name]').val(rowData.name || '');
        this.$form_report.find('[id=status]').attr('checked', rowData.status === undefined ? true : rowData.status > 0);
        this.$form_report.find('[id=sql]').val(rowData.sql || '');
        this.$form_report.find('[id="rcId"]').append(
            _.template('<option value="{{value}}">{{label}}</option>')({ value: node.id, label: node.name })
        );
        this.reportMateTable.addRows(JSON.parse(rowData.metaColumns || '[]'));
        // 避免火狐浏览器两次动画bug
        setTimeout(function () {
            // 初始化数据源
            $('#rdsId').xumf_select({
                url: _.template(ReportBaseDesign.URL.DATA_SOURCE_GET)({ reportId: '' }),
                select: [{
                    value: rowData.rdsId,
                    selected: true
                }]
            })
        }, 10);
    },
    /**
     * sql编辑器初始化
     */
    initSqlEditor: function () {
        var self = this;
        // 添加table事件
        this.reportParamTable.byDelegateEvent();
        var rowData = this.rowData;
        // 初始化sql编辑器
        var editor = CodeMirror.fromTextArea(document.getElementById('sql'), {
            mode: 'text/x-plsql',
            theme: 'solarized dark',
            indentWithTabs: true,
            smartIndent: true,
            lineNumbers: true,
            matchBrackets: true,
            autofocus: true,
            extraKeys: { "Ctrl-Space": "autocomplete" },
            hintOptions: {
                tables: {
                    users: ["name", "score", "birthDate"],
                    countries: ["name", "population", "size"]
                }
            }
        });
        editor.on("change", function (editor, changes) {
            self.$form_report.find('[id="sql"]').val(editor.getValue());
        });
        // 设置默认值
        editor.setValue(rowData.sql || '');
    }
};